from flask import Blueprint, jsonify, request
from app.models.focus_session import FocusSession
from app.models.goal import Goal
from app.models.setting import Setting
from app.models.statistic import Statistic
from app import db
import json
from datetime import datetime, timedelta
import os

api = Blueprint('api', __name__)

# 强制修正年份为2024年的辅助函数
def correct_year(dt):
    """修正年份为2024年"""
    if not dt:
        return None
    if dt.year >= 2025:
        return dt.replace(year=2024)
    return dt

# 添加新的时间处理函数
def process_datetime(iso_time_str):
    """处理ISO时间字符串，确保正确的时区转换"""
    if not iso_time_str:
        return None
    
    try:
        # 处理ISO格式，确保时区信息正确
        time_str = iso_time_str.replace('Z', '+00:00')
        dt = datetime.fromisoformat(time_str)
        
        # 修正年份
        dt = correct_year(dt)
        
        # 转换为本地时区 (可选，取决于应用需求)
        # 如果已经是UTC时间且需要显示本地时间，可以进行时区转换
        # 这里我们保持原始时间，因为后续显示时会考虑时区
        
        return dt
    except Exception as e:
        print(f"处理时间出错: {e}")
        return None

# 设置相关API
@api.route('/settings', methods=['GET'])
@api.route('/settings/', methods=['GET'])  # 添加尾部斜杠路由
def get_settings():
    setting = Setting.query.first()
    if not setting:
        return jsonify({})
    return jsonify(setting.to_dict())

@api.route('/settings', methods=['PUT'])
@api.route('/settings/', methods=['PUT'])  # 添加尾部斜杠路由
def update_settings():
    setting = Setting.query.first()
    if not setting:
        setting = Setting()
        db.session.add(setting)
    
    data = request.get_json()
    # 处理基本字段
    for field in ['focus_duration', 'short_break_duration', 'long_break_duration', 
                 'long_break_interval', 'auto_start_break', 'auto_start_focus']:
        if field in data:
            setattr(setting, field, data[field])
    
    # 特殊处理JSON字段
    if 'notification' in data:
        setting.set_json_field('notification', data['notification'])
    
    if 'sound' in data:
        setting.set_json_field('sound', data['sound'])
    
    if 'theme' in data:
        setting.set_json_field('theme', data['theme'])
    
    db.session.commit()
    return jsonify(setting.to_dict())

# 专注会话相关API
@api.route('/focus-sessions', methods=['GET'])
@api.route('/focus-sessions/', methods=['GET'])  # 添加尾部斜杠路由
def get_focus_sessions():
    sessions = FocusSession.query.order_by(FocusSession.start_time.desc()).all()
    return jsonify([session.to_dict() for session in sessions])

@api.route('/focus-sessions', methods=['POST'])
@api.route('/focus-sessions/', methods=['POST'])  # 添加尾部斜杠路由
def create_focus_session():
    data = request.get_json()
    
    # 详细记录接收到的时间数据
    print(f"接收到创建会话请求数据: {data}")
    
    # 使用服务器当前时间计算
    current_server_time = datetime.now()  # 使用服务器本地时间
    
    # 如果前端提供了持续时间，则使用它，否则默认为0
    duration_seconds = data.get('duration', 0)
    
    # 根据持续时间计算开始时间
    start_time = current_server_time - timedelta(seconds=duration_seconds)
    
    # 创建会话记录，使用服务器计算的时间
    session = FocusSession(
        type=data.get('type', 'focus'),
        start_time=start_time,
        end_time=current_server_time,
        duration=duration_seconds,
        goal_id=data.get('goal_id'),
        completed=data.get('completed', True),
        quality=data.get('quality'),
        note=data.get('note')
    )
    
    db.session.add(session)
    
    # 如果会话关联了目标，更新目标进度
    if data.get('goal_id'):
        goal = Goal.query.get(data.get('goal_id'))
        if goal:
            # 计算会话持续的分钟数（向上取整，确保不会丢失时间）
            minutes = (duration_seconds + 59) // 60  # 向上取整，确保不会少算时间
            
            # 记录更新前的信息
            print(f"目标 {goal.id} 更新前: 已完成时间={goal.completed_time}分钟, 目标时间={goal.target_time}分钟")
            
            # 更新目标完成时间
            goal.completed_time += minutes
            
            # 检查目标是否完成
            if goal.completed_time >= goal.target_time:
                goal.completed = True
                print(f"目标 {goal.id} 已完成!")
            
            # 更新目标的最后修改时间为服务器当前时间
            goal.updated_at = current_server_time
            
            # 记录更新后的信息
            print(f"目标 {goal.id} 更新后: 已完成时间={goal.completed_time}分钟, 目标时间={goal.target_time}分钟")
    
    # 提交所有更改
    db.session.commit()
    
    # 记录存储到数据库的实际时间值
    print(f"存储到数据库的开始时间: {session.start_time}")
    print(f"存储到数据库的结束时间: {session.end_time}")
    print(f"会话持续时间: {session.duration}秒，约{session.duration//60}分钟")
    
    return jsonify(session.to_dict()), 201

@api.route('/focus-sessions/<int:id>', methods=['PUT'])
def update_focus_session(id):
    session = FocusSession.query.get_or_404(id)
    data = request.get_json()
    
    # 特殊处理日期时间字段
    if 'start_time' in data and data['start_time']:
        try:
            # 记录接收到的时间字符串
            print(f"接收到的开始时间: {data['start_time']}")
            # 解析ISO格式字符串为带时区的datetime对象
            session.start_time = datetime.fromisoformat(data['start_time'].replace('Z', '+00:00'))
            # 记录解析后的时间
            print(f"解析后的开始时间: {session.start_time}")
        except Exception as e:
            print(f"解析开始时间出错: {e}")
            pass
    
    if 'end_time' in data and data['end_time']:
        try:
            # 记录接收到的时间字符串
            print(f"接收到的结束时间: {data['end_time']}")
            # 解析ISO格式字符串为带时区的datetime对象
            session.end_time = datetime.fromisoformat(data['end_time'].replace('Z', '+00:00'))
            # 记录解析后的时间
            print(f"解析后的结束时间: {session.end_time}")
        except Exception as e:
            print(f"解析结束时间出错: {e}")
            pass
    
    # 处理其他简单字段
    for field in ['type', 'duration', 'goal_id', 'completed', 'quality', 'note']:
        if field in data:
            setattr(session, field, data[field])
    
    db.session.commit()
    return jsonify(session.to_dict())

@api.route('/focus-sessions/<int:id>', methods=['DELETE'])
def delete_focus_session(id):
    session = FocusSession.query.get_or_404(id)
    db.session.delete(session)
    db.session.commit()
    return '', 204

# 目标相关API
@api.route('/goals', methods=['GET'])
@api.route('/goals/', methods=['GET'])  # 添加尾部斜杠路由
def get_goals():
    goals = Goal.query.all()
    return jsonify([goal.to_dict() for goal in goals])

# 添加获取单个目标的路由
@api.route('/goals/<int:id>', methods=['GET'])
def get_goal(id):
    goal = Goal.query.get_or_404(id)
    return jsonify(goal.to_dict())

@api.route('/goals', methods=['POST'])
@api.route('/goals/', methods=['POST'])  # 添加尾部斜杠路由
def create_goal():
    data = request.get_json()
    
    # 创建目标实例
    goal = Goal(
        name=data.get('name'),
        description=data.get('description'),
        category=data.get('category'),
        target_time=data.get('target_time'),
        completed_time=data.get('completed_time', 0),
        completed=data.get('completed', False),
        priority=data.get('priority')
    )
    
    # 处理日期字段
    if 'deadline' in data and data['deadline']:
        try:
            goal.deadline = datetime.fromisoformat(data['deadline'])
        except:
            goal.deadline = None
    
    # 处理标签
    goal.set_tags(data.get('tags', []))
    
    db.session.add(goal)
    db.session.commit()
    return jsonify(goal.to_dict()), 201

@api.route('/goals/<int:id>', methods=['PUT'])
def update_goal(id):
    goal = Goal.query.get_or_404(id)
    data = request.get_json()
    
    # 记录更新前的状态
    print(f"更新目标前: ID={goal.id}, 名称={goal.name}, 已完成时间={goal.completed_time}分钟, 目标时间={goal.target_time}分钟, 是否完成={goal.completed}")
    
    # 处理基本字段
    for field in ['name', 'description', 'category', 'target_time', 
                'priority']:
        if field in data:
            setattr(goal, field, data[field])
    
    # 特别处理completed_time字段，确保它是整数
    if 'completed_time' in data:
        try:
            completed_time = int(data['completed_time'])
            goal.completed_time = completed_time
            
            # 自动检查目标是否完成
            if goal.completed_time >= goal.target_time:
                goal.completed = True
            elif 'completed' not in data:  # 只有在用户没有明确设置completed时才自动设为False
                goal.completed = False
        except (ValueError, TypeError) as e:
            print(f"处理completed_time出错: {e}")
    
    # 明确处理completed字段
    if 'completed' in data:
        goal.completed = bool(data['completed'])
    
    # 处理日期字段
    if 'deadline' in data:
        if data['deadline']:
            try:
                goal.deadline = datetime.fromisoformat(data['deadline'])
            except Exception as e:
                print(f"处理deadline出错: {e}")
        else:
            goal.deadline = None
    
    # 处理标签
    if 'tags' in data:
        goal.set_tags(data['tags'])
    
    # 更新时间戳为服务器当前时间
    goal.updated_at = datetime.now()
    
    # 记录更新后的状态
    print(f"更新目标后: ID={goal.id}, 名称={goal.name}, 已完成时间={goal.completed_time}分钟, 目标时间={goal.target_time}分钟, 是否完成={goal.completed}")
    
    db.session.commit()
    return jsonify(goal.to_dict())

@api.route('/goals/<int:id>', methods=['DELETE'])
def delete_goal(id):
    goal = Goal.query.get_or_404(id)
    db.session.delete(goal)
    db.session.commit()
    return '', 204

# 统计数据相关API
@api.route('/statistics', methods=['GET'])
@api.route('/statistics/', methods=['GET'])  # 添加尾部斜杠路由
def get_statistics():
    stats = Statistic.query.order_by(Statistic.date.desc()).all()
    return jsonify([stat.to_dict() for stat in stats])

@api.route('/statistics/daily', methods=['GET'])
def get_daily_statistics():
    date = request.args.get('date')
    if date:
        stat = Statistic.query.filter_by(date=date).first()
        if stat:
            return jsonify(stat.to_dict())
    return jsonify({}) 